<template>
  <el-row
      :gutter="10"
      justify="start"
      style="background: linear-gradient(to right, #f8c06d, #f58147); padding: 15px 0; border-radius: 8px; margin-bottom: 20px"
  >
    <el-col :span="12">
      <h2 style="color: #fff; font-size: 24px; margin: 0; padding-left: 10px; text-align: left;color: #363644">菜品管理</h2>
    </el-col>
  </el-row>

  <el-row :gutter="10" justify="start">
    <el-col :span="7">
      <label id="cpid" style="margin-left: 20px">菜品编号:</label>
      <el-input style="width: 160px" name="cpid" v-model="caiPin.cpid" placeholder="请输入菜品id"></el-input>
    </el-col>
    <el-col :span="2">
      <el-button type="primary" @click="doList">查询</el-button>
    </el-col>
    <el-col :span="2">
      <el-button type="primary" @click="reset">重置</el-button>
    </el-col>
    <el-col :span="2">
      <el-button type="success" @click="showAddDialog">+新增菜品</el-button>
    </el-col>
    <el-col :span="2" id = "batchDelete">
      <el-button type="danger" @click="batchDelete" >批量删除</el-button>
    </el-col>

  </el-row>
  <el-row id = "caipin-table" justify="start">
    <el-table
        stripe
        :data="currentPageData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" min-width="50"></el-table-column>
      <el-table-column prop="cpid" label="菜品id"></el-table-column>
      <el-table-column prop="cpmc" label="菜品名称"></el-table-column>
      <el-table-column prop="count" label="数量"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="info" size="small" @click="doDetail(scope.row)">详情</el-button>
          <el-button type="primary" size="small" @click="showUpdateDialog(scope.row)">修改</el-button>
          <el-button type="danger" size="small" @click="doDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-container" :data="currentPageData" style="margin: 20px auto">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 8, 10, 20, 50]"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-row>

  <!-- 新增 dialog-->
  <el-dialog v-model="addDialogVisible" width="40%" top="2vh" destroy-on-close>
    <add-cai-pin
        @flushPage="reset"
        @closeDialog="addDialogVisible = false">
    </add-cai-pin>
  </el-dialog>

  <!-- 更新 dialog-->
  <el-dialog v-model="updateDialogVisible" width="40%" top="2vh" destroy-on-close>
    <update-cai-pin ref="updatePageRef"
                     @flushPage="reset"
                     @closeDialog="updateDialogVisible = false">
    </update-cai-pin>
  </el-dialog>

<!--  详情 dialog-->
  <div>
    <cai-pin-detail ref="caiPinDetailRef" v-model="detailDialogVisible"></cai-pin-detail>
  </div>
</template>

<script setup >
import {computed, nextTick, onMounted, reactive, ref} from 'vue'
import axios from "axios";
import {ElMessage,ElMessageBox} from "element-plus";
import AddCaiPin from "./AddCaiPin.vue";
import UpdateCaiPin from "./UpdateCaiPin.vue";
import CaiPinDetail from "./CaiPinDetail.vue";

const caiPin = reactive({
  cpid: '',
})
const caiPinList = ref()

//------------------------ 批量删除------------------------
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
const batchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请至少选择一条数据");
    return;
  }
  const confirmResult = await ElMessageBox.confirm(
      "确定要删除选中的菜品吗？",
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
  ).catch(() => {
    ElMessage.info("已取消删除");
    return false;
  });

  if (!confirmResult) return;

  const cpids = multipleSelection.value.map((item) => parseInt(item.cpid)).join(",");


  try {
    const { data } = await axios.delete(`/api/caiPin/batch`, { data: { cpids } });
    if (data.code === 200) {
      ElMessage.success("批量删除成功");
      await doList();
    } else {
      ElMessage.error(data.message || "删除失败");
    }
  } catch (error) {
    ElMessage.error("请求失败，请重试");
    console.error(error);
  }
};


onMounted(() =>{
  doList();
})

//----------------------------分页--------------------------
// 分页相关变量
const total = ref(0)
const pageSize = ref(5)
const currentPage = ref(1)

// 计算当前页的数据
const currentPageData = computed(() => {
  if (!Array.isArray(caiPinList.value)) {
    return [];
  }
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return caiPinList.value.slice(start, end);
});

// 分页事件处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 切换每页条数时，返回第一页
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

//分页重置
const doPageReset = () => {
  total.value = 0;
  currentPage.value = 1;
  pageSize.value = 5;
}

// 刷新页面
const flushPage = () => {
  doPageReset();
  doList();
}

// ----------------------------查询--------------------------
// 在查询接口中，确保后端返回 total 数据，如果没有则计算
const doList = async () => {
  caiPinList.value = [];
  const url = caiPin.cpid ? `/api/caiPin/${caiPin.cpid}` : '/api/caiPin';
  const { data } = await axios.get(url);
  if (data.code === 200) {
    if (caiPin.cpid) {
      caiPinList.value = [data.data];
      total.value = 1; // 单条数据时总条数为 1
    } else {
      caiPinList.value = data.data || [];
      total.value = data.total || data.data.length; // 建议后端返回 total 字段
    }
    ElMessage.success('查询成功');
  } else {
    ElMessage.error(data.message);
  }
}



const reset = () => {
  caiPin.cpid = '';
  flushPage();  // 刷新页面
  doList();
}

const detailDialogVisible = ref(false)
const caiPinDetailRef = ref();  //引用组件
const doDetail = (obj) => {
  detailDialogVisible.value = true;
  nextTick(()=>{
    caiPinDetailRef.value.handleDetailData(obj);
  })
}

const addDialogVisible = ref(false)
const showAddDialog = () => {
  addDialogVisible.value = true;
}

const updateDialogVisible = ref(false)
const updatePageRef = ref();
const showUpdateDialog = (row) => {
  updateDialogVisible.value = true;
  nextTick(()=>{
    updatePageRef.value.handleUpdateData(row);
  })
}

const doDelete = async (row) => {
  const {data} = await axios.delete(`/api/caiPin/${row.cpid}`)
  console.log(data);
  if(data.code === 200){
    ElMessage.success('删除成功');
    flushPage() // 刷新页面
    await doList();
  }else{
    ElMessage.error(data.message);
  }
}

</script>

<style scoped>

#caipin-table{
  margin-top: 20px;
}

#batchDelete{
margin-left: 300px;
}
</style>